from django.core.urlresolvers import reverse
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,redirect
from myadmin import models


from django.contrib.auth.hashers import make_password, check_password

from lzy.settings import BASE_DIR
import os



# 文件上传的函数
def uploads(myfile):
    import time,random
    from lzy.settings import BASE_DIR

    filename = str(time.time())+str(random.randint(10000,99999))+'.'+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    return "/static/pics/"+filename





# 添加商品
def cartadd(request):

    try:
        gid = request.GET['gid']
        num = int(request.GET['num'])
        # 接收数据,商品id,购买数量
        ob = models.Goods.objects.get(id=gid)
        # 准备数据
        goods = {'gid':ob.id,'title':ob.title,'price':ob.price,'pic':ob.pic,'num':num}

        # 获取购物车的数据
        data = request.session.get('Cart',{})
        # 判断当前数据是否在购物车中
        if gid in data:
            # 存在,修改
            data[gid]['num'] += num
        else:
            # 不存在则添加
            data[gid] = goods
        # 重新存入购物车
        request.session['Cart'] = data

        return JsonResponse({'error':0,'msg':'加入购物车成功'})
    except:
        return JsonResponse({'error':1,'msg':'加入购物车失败'})

# 购物车列表
def cartindex(request):
    
    return render(request,'home/cart/index.html')
 # 清空购物车 
def cartclear(request):   
    
    request.session['Cart'] = ()

    return HttpResponse('cartclear')

# 删除商品
def cartdelete(request,gid):    
    # 获取购物车的数据
    data = request.session.get('Cart',{})
    del data[gid]

    # 把修改好的购物车数据,重新存入session
    request.session['Cart'] = data

    return  HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')


# 修改商品数量
def cartedit(request):
     
    gid = request.GET.get('gid')
    num = int(request.GET.get('num'))

     # 获取购物车的数据
    data = request.session['Cart']
    # 修改商品购买的数量
    data[gid]['num'] = num
    # 把购物车重新输入session
    request.session['Cart'] = data

    return HttpResponse('<script>location.href="'+reverse('myhome_cartindex')+'"</script>')


# 确认订单
def orderconfirm(request):
    # 接收传递数据
    ids = request.GET.get('ids')
    ids = ids.split(',')
    # 购物车数据
    cart = request.session.get('Cart')
    data = {}
    for x in ids:
        data[x] = cart[x]


    # 获取当前用户的所有收货地址
    adds = models.Address.objects.filter(uid=request.session['VipUser']['uid'])
    print(adds)

    # 分配数据
    context = {'data':data,'adds':adds}
    print(adds)
    
    # 加载模板
    return render(request,'home/order/confirm.html',context)



# 添加收货地址
def addressinsert(request):
    # 接受数据
    data = request.GET.dict()
    # 获取用户对象
    data['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])


    # 判断是否为默认
    if data['status'] == '1':
        data['status'] = True
        # 把其它的地址改为非默认
        obs = models.Address.objects.filter(uid=data['uid'])
        for x in obs:
            x.status = False
            x.save()

    # 执行添加
    ob = models.Address.objects.create(**data)


    return JsonResponse({'error':0,'msg':'地址添加成功'})


    



# 生成订单
def ordercreate(request):
    try:
        # 接收数据 [1,2]
        ids = request.POST.get('ids')

        print(ids)
        ids = ids.split(',')
        addid = request.POST.get('addid')

        # 生成订单
        orderdata ={}
        orderdata['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])
        orderdata['aid'] = models.Address.objects.get(id=addid)
        orderdata['totalprice'] = 0
        ob =models.Order.objects.create(**orderdata)

        # 获取购物车的数据
        cart = request.session['Cart']
        totalprice = 0

        # 订单详情
        for x in ids:
          # 创建订单的详情
          res = models.OrderInfo()
          res.orderid = ob
          goods = models.Goods.objects.get(id=x)
          res.goodsid = goods
          res.price = goods.price
          res.num = cart[x]['num']
          res.save()
          
          # 删除购物车的已购买的商品
          del cart[x]

          # 运算总价
          totalprice += res.price*res.num

          # 减去库存余量
          goods.num -= res.num

          goods.save()
        # 购物车的数据重新存入sssion
        request.session['Cart'] = cart

        ob.totalprice = totalprice
        ob.save()

        return HttpResponse('<script>alert("请支付");location.href="/order/buy/'+str(ob.id)+'/"</script>')
    except:
        return HttpResponse('<script>alert("打扰了");location.href="home/order/confirm.html"</script>')


# 支付页面
def orderbuy(request,oid):

    # 根据订单id获取订单信息
    ob = models.Order.objects.get(id=oid)

    context = {'order':ob}


    return render(request,'home/order/buy.html',context)

# 付款
def orderbuysuccess(request,oid):
    
    # 根据订单id获取订单信息
    ob = models.Order.objects.get(id=oid)

    ob.status = 1
    ob.save()

    return render(request,'home/order/success.html')

# 取消付款
def ordernobuysuccess(request,oid):
    # 根据订单id获取订单信息
    ob = models.Order.objects.get(id=oid)

    ob.status = 0
    ob.save()

    return render(request,'home/center/myorder.html')
    

# 我的订单
def myorder(request):
    
    # 获取当前用户对象的所有订单
    orderlist =models.Order.objects.filter(uid=request.session['VipUser']['uid'])

     # 接受参数
    types = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    # 判断是否有搜索条件
    if types:
        if types == 'all':
        # 多字段的查询
            from django.db.models import Q
            users = orderlist.filter(Q(username__contains=keywords)|Q(email__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords))
        else:
            data ={types+'__contains':keywords}
            users = orderlist.filter(**data)
     # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(orderlist,10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    orderlist = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range

    # 分配数据

    context = {'orderlist':orderlist}
    return render(request,'home/center/myorder.html',context)



# 个人中心
def mycenter(request):
   
    # 获取用户对象
    center = models.Users.objects.filter(id=request.session['VipUser']['uid'])
    print(center)
    context = {'center':center}
    print(context)

    return render(request,'home/center/mycenter.html',context)

# 编辑修改个人信息
def editcenter(request,uid):
    # 通过id获取用户数据
    ob = models.Users.objects.get(id=uid)

    # 分配数据
    context = {'uinfo':ob}

    # 返回模板页面
    return render(request,'home/center/editcenter.html',context)

# 执行修改
def updatecenter(request):
    try:
        # 接收数据
        data = request.POST.dict()
        # print(data)
        # data.pop('csrfmiddlewaretoken') 
        # 获取对象
        ob = models.Users.objects.get(id=data['id'])
        # 更新属性
        ob.username = data['username']
        ob.password = data['password']
        ob.phone = data['phone']
        ob.email = data['email']
        ob.sex = data['sex']
        ob.age = data['age']

        # 判断是否有文件上传
        myfile = request.FILES.get('pic',None)
        if myfile:
            
            # 执行文件上传,并更新头像数据
            ob.pic = uploads(myfile)
        # 执行更新    
        ob.save()
        # 操作成功
        return HttpResponse('<script>alert("更新成功");location.href="'+reverse('myhome_mycenter')+'"</script>')
    except:
        # 操作失败
        return HttpResponse('<script>alert("更新失败");location.href="'+reverse('myadmin_user_index')+'"</script>')



# 我的地址
def mysite(request):    

     # 接受数据
    data = request.GET.dict()
    # 获取用户对象
    data['uid'] = models.Users.objects.get(id=request.session['VipUser']['uid'])

    # 获取当前用户的所有收货地址
    sitelist =  models.Address.objects.filter(uid=data['uid'])

    context = {'sitelist':sitelist}

    return render(request,'home/center/mysite.html',context)



# 删除地址
def delsite(request,oid):
    # 获取用户点击的地址id
    sitelist =  models.Address.objects.filter(id=oid)
    # 执行删除
    sitelist.delete()
    # 重定向
    return  redirect(reverse('myhome_mysite'))


# 修改地址信息
def editsite(request):
    try:
       # 获取数据
        data = request.POST.dict()
        # 获取用户点击的地址id
        ob = models.Address.objects.get(id=data['id'])
        # 执行修改更新
        ob.addressname = data['addressname']
        ob.address = data['address']
        ob.addressphone = data['addressphone']
        # 是否默认
        isdefault = data.get('status',None)
        if isdefault:
            uid = request.session['VipUser']['uid']
            try:
                defaultaddr = models.Address.objects.filter(uid=uid).get(status=True)
            except:
                defaultaddr = None
            if defaultaddr:
                defaultaddr.status = False
                defaultaddr.save()
            ob.status = True
        else:
            ob.status = False
        ob.save()
        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myhome_mysite')+'"</script>')
    except:
        return HttpResponse('<script>alert("修改失败");location.href="'+reverse('myhome_mysite')+'"</script>')


























